#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import json

from common.parse_parafile import ParamFileUtil
from common.cleaner import clear

from ndmp.comm.log import log
from ndmp.comm.param_base import ParamBase
from ndmp.comm.utils import get_env_in_variable


class ResourceParam(ParamBase):
    def __init__(self, req_id):
        super().__init__(req_id)
        self._application: dict = dict()
        self._appenv: dict = dict()
        self._auth_flag = True
        self.parse_param()

    def parse_param(self):
        """
        鉴权参数结构:
        {
            "appEnv": {
                ...
            },
            "application": {
                "auth": {
                    "extendInfo": null
                },
                "extendInfo": {
                    "ndmpServerGap": "1",
                    "ndmpSrc": "{\"serverIp\":\"192.168.102.166\",\"port\":10000}",
                    "version": "v4"
                },
                ...
            }
        }
        资源浏览参数结构:
        {
            'appEnv': {
                ...
            },
            'applications': [
                {
                    "auth": {
                        "extendInfo": null
                    },
                    "extendInfo": {
                        "ndmpServerGap": "1",
                        "ndmpSrc": "{\"serverIp\":\"192.168.102.166\",\"port\":10000}",
                        "version": "v4"
                    },
                    ...
                }
            ],
            'condition': {
            'conditions': None,
            'pageNo': 0,
            'pageSize': 200
            }
        }
        """
        try:
            self._param = ParamFileUtil.parse_param_file(self.req_id)
        except Exception as err:
            raise Exception(f"Failed to parse job param file for {err}") from err
        if not self._param:
            raise Exception(f"Failed to parse job param file is none")
        if "application" in self._param.keys():
            self._application = self._param.get("application", {})
            self._appenv = self._param.get("appEnv", {})
        else:
            self._application = self._param.get("applications", [])[0]
            self._appenv = self._param.get("appEnv", {})
            self._auth_flag = False

    def clear(self):
        """
        清理敏感信息
        :return:
        """
        clear(self.get_src_auth())
        clear(self.get_dst_auth())
        clear(self.get_src_pwd())
        clear(self.get_dst_pwd())

    def get_src_path(self):
        src_path = json.loads(self._application.get("extendInfo", {}).get("ndmpSrc")).get("path")
        return src_path

    def get_dst_path(self):
        dst_path = json.loads(self._application.get("extendInfo", {}).get("ndmpDst")).get("path")
        return dst_path

    def get_src_ip(self):
        src_ip = self._appenv.get("endpoint")
        return src_ip

    def get_dst_ip(self):
        dst_ip = self._appenv.get("endpoint")
        return dst_ip

    def get_dst_port(self):
        dst_port = self._appenv.get("port")
        return dst_port

    def get_src_auth(self):
        """
        获取本端用户名
        """
        if self._auth_flag:
            src_auth = get_env_in_variable(f"application_auth_extendInfo_authKey_{self.req_id}")
        else:
            src_auth = get_env_in_variable(f"applications_0_auth_extendInfo_authKey_{self.req_id}")
        return src_auth

    def get_dst_auth(self):
        """
        获取远端端用户名
        """
        dst_auth = get_env_in_variable(f"appEnv_auth_authKey_{self.req_id}")
        return dst_auth

    def get_src_pwd(self):
        """
        获取本端用户密码
        """
        if self._auth_flag:
            src_pwd = get_env_in_variable(f"application_auth_extendInfo_authPwd_{self.req_id}")
        else:
            src_pwd = get_env_in_variable(f"applications_0_auth_extendInfo_authPwd_{self.req_id}")
        return src_pwd

    def get_dst_pwd(self):
        """
        获取远端用户密码
        """
        dst_pwd = get_env_in_variable(f"appEnv_auth_authPwd_{self.req_id}")
        return dst_pwd

    def get_server_gap(self):
        return self._appenv.get("extendInfo", {}).get("ndmpServerGap", "0")
